package com.ironone.streaming.comm;

import java.io.IOException;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.util.Log;

/**
 * {Parsing XML}
 * 
 * @Created on Dec 09, 2014
 * @author Helani
 */

public class XMLParser {

	/*
	 * Parsing XML content and getting DOM element
	 * 
	 * DOM:In the DOM, everything is a node. Element nodes do not have a text
	 * value. The text of an element node is stored in a child node. This node
	 * is called a text node.
	 * 
	 * After getting XML content we need to get the DOM element of the XML file.
	 * Below function will parse the XML content and will give you DOM element.
	 */

	public Document getDomElement(String xml) {
		Document doc = null;
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		try {

			DocumentBuilder db = dbf.newDocumentBuilder();

			InputSource is = new InputSource();
			is.setCharacterStream(new StringReader(xml));
			doc = db.parse(is);

		} catch (ParserConfigurationException e) {
			Log.e("Error: ", e.getMessage());
			return null;
		} catch (SAXException e) {
			Log.e("Error: ", e.getMessage());
			return null;
		} catch (IOException e) {
			Log.e("Error: ", e.getMessage());
			return null;
		}
		// reurn DOM
		return doc;
	}

	/* Get each xml child element value by passing element node name */
	public String getValue(org.w3c.dom.Element item, String str) {
		NodeList n = item.getElementsByTagName(str);
		// NodeList n = ((Document) item).getElementsByTagName(str);
		return this.getElementValue(n.item(0));
	}

	public final String getElementValue(Node elem) {
		Node child;
		if (elem != null) {
			if (elem.hasChildNodes()) {
				for (child = elem.getFirstChild(); child != null; child = child
						.getNextSibling()) {
					if (child.getNodeType() == Node.TEXT_NODE) {
						return child.getNodeValue();
					}
				}
			}
		}
		return "";
	}

}
